package com.heima.comment.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import net.sf.jsqlparser.statement.select.Limit;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.Size;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private GreenTextScan greenTextScan;


    @Autowired
    private UserFeign userFeign;

    /**
     * 加载回复评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        String commentId = dto.getCommentId();
        //1. 校验参数
        //   评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        Date minDate = dto.getMinDate();
        if (minDate == null) {
            minDate = new Date();
        }

        //2. 条件查询评论回复信息
        //	条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(commentId)
                .and("createdTime").lt(minDate)).limit(size);
        //降序
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);// 排序
        //查询
        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);

        //
        //3. 检查是否登录   没有登录 直接返回评论回复集合
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //	3.1 如果未登录直接 返回评论回复列表
            return ResponseResult.okResult(apCommentRepayList);
        }
        //
        //	3.2 如果登录，需要判断哪些回复点过赞
        //	思路:
        //	     基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        //	     遍历 当前回复列表，将每一个回复信息 封装成 vo
        List<ApCommentRepayLike> apLikeList = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepayList) {
            //获取每一条评论的id
            String id = apCommentRepay.getId();
            //获取查询条件
            Query query1 = Query.query(Criteria.where("commentRepayId").is(id)
                    .and("authorId").is(user.getId()));
            //查询回复点赞列表中 有多少是被点赞的回复
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query1, ApCommentRepayLike.class);
            if (apCommentRepayLike != null && apCommentRepayLike.getOperation() == 0){
                apLikeList.add(apCommentRepayLike);
            }
        }

        if (CollectionUtils.isEmpty(apLikeList)){
            return ResponseResult.okResult(apCommentRepayList);
        }


        //	     判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
        boolean fale = false;
        List<ApCommentRepayVO> apCommentRepayVOS = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepayList) {
            //创建vo对象 并封装
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);
            //判断数据是否被点赞
            for (ApCommentRepayLike apCommentRepayLike : apLikeList) {
                if (apCommentRepayLike.getCommentRepayId().equals(apCommentRepay.getId())) {
                    //说明回复被点赞了
                    apCommentRepayVO.setOperation((short) 0);
                    apCommentRepayVOS.add(apCommentRepayVO);
                    fale = true;
                    break;
                }
                fale = false;
            }
            if (!fale){
                apCommentRepayVOS.add(apCommentRepayVO);
            }
        }

        //返回修改之后的vo对象
        return ResponseResult.okResult(apCommentRepayVOS);
    }


    /**
     * 保存回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1. 参数校验:
        //   是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录哦");
        }

        //   回复内容安全校验
        //        简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**

        try {
            Map resultMap = greenTextScan.greenTextScan(dto.getContent());
            //       (简单:  此步不做      普通: 阿里云检测有问题提示      高级:  有问题不报异常，替换为**)
            String suggestion = resultMap.get("suggestion").toString();
            if (!"pass".equals(suggestion)) {
                Object filteredContent = resultMap.get("filteredContent");
                if (filteredContent != null) {
                    String str = filteredContent.toString();
                    dto.setContent(str);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        //远程调用feign  查询登录的用户信息
        ResponseResult<ApUser> result = userFeign.findUserById(user.getId());
        if (result.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApUser apUser = result.getData();

        //2. 根据评论id查询评论信息  检查是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该评论不存在无法回复");
        }

        //3. 保存评论回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);

        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());

        mongoTemplate.save(apCommentRepay);

        //4. 修改评论信息中回复数量 + 1
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(apCommentRepay);
    }


    /**
     * 保存回复点赞信息
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //       回复id不能为空   operation 必须 0 或 1
        //       校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录");
        }

        //       校验回复信息是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(query, ApCommentRepay.class);
        if (apCommentRepay == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该评论不存在不能点赞哦");
        }

        //判断是否点过赞
        Query query1 = Query.query(Criteria.where("commentRepayId").is(apCommentRepay.getId()));
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query1, ApCommentRepayLike.class);


        //2. 如果是点赞  判断是否点过赞
        if (dto.getOperation() == 0) {
            //      点过赞提示请勿重复点赞
            if (apCommentRepayLike == null) {
                //      未点过赞， 保存点赞信息
                ApCommentRepayLike apCommentRepayLike1 = new ApCommentRepayLike();

                apCommentRepayLike1.setAuthorId(user.getId());
                apCommentRepayLike1.setCommentRepayId(apCommentRepay.getId());
                apCommentRepayLike1.setOperation((short) 0);

                //保存回复点赞信息
                apCommentRepayLike = mongoTemplate.save(apCommentRepayLike1);

            } else {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "重复点赞");
            }

            //       并将回复信息的点赞数量字段+1
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);

            //修改点赞表
            apCommentRepayLike.setOperation((short) 0);
            mongoTemplate.save(apCommentRepayLike);

            //返回数据
            HashMap<String, Object> map = new HashMap<>();
            map.put("likes", apCommentRepay.getLikes());
            return ResponseResult.okResult(map);

        }

        //3. 如果是取消赞

        //      删除点赞信息
        mongoTemplate.remove(apCommentRepayLike);

        //     并将回复信息的点赞数量字段 -1
        Integer likes = apCommentRepay.getLikes();
        likes = likes - 1;
        if (likes - 1 < 0) {
            likes = 0;
        }
        //修改评论表
        apCommentRepay.setLikes(likes);
        mongoTemplate.save(apCommentRepay);

        //4. 返回当前回复的最新点赞数量      数据的key:  likes
        HashMap<String, Object> map = new HashMap<>();
        map.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(map);
    }
}
